class Snake{

    //获取蛇头
    head:HTMLElement;
    //包括蛇头
    bodies:HTMLCollection;
    //获取蛇容器
    element:HTMLElement;


    //构造器
    constructor(){
        this.element = document.getElementById("snake")!;
        this.head = document.querySelector("#snake>div")! as HTMLElement;
        this.head.className="headStyle"
        this.bodies =  this.element.getElementsByTagName("div");
    }


    //坐标  蛇头x
    get X(){
        return this.head.offsetLeft;
    }

     //坐标  蛇头Y
    get Y(){
        return this.head.offsetTop;
    }

    
    set X(value:number){
        if(this.X===value) {
            return;
        }
        // 撞墙
        if(value<0||value>390){
            throw new Error("撞墙了，阿欧！")
        }

        //向一个方向走不能反方向
        if(this.bodies[1] && (this.bodies[1] as HTMLElement) .offsetLeft===value){
            if(value>this.X){
                value=this.X-10
            }else{
                value=this.X+10
            }
        }

        this.moveBody()
        this.head.style.left = `${value}px`
        this.checkHeadBoy()
    }

    set Y(value:number){
        if(this.Y===value){
            return;
        }
        // 撞墙
        if(value<0||value>390){
            throw new Error("撞墙了，阿欧！")
        }

        //向一个方向走不能反方向
        if(this.bodies[1] && (this.bodies[1] as HTMLElement) .offsetTop===value){
            if(value>this.Y){
                value=this.Y-10
            }else{
                value=this.Y+10
            }
        }

        this.moveBody()
        this.head.style.top = `${value}px`
        this.checkHeadBoy()
    }

    //增加身体
    addBody(){
        this.element.insertAdjacentHTML("beforeend","<div></div>")
    }

    //身体 移动
    moveBody(){
        //身体一节一节移动
        
        for (let index = this.bodies.length-1; index > 0 ;index--) {
            let X = (this.bodies[index-1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[index-1] as HTMLElement).offsetTop;

            //设置到当前位置
            (this.bodies[index] as HTMLElement).style.left = `${X}px`;
            (this.bodies[index] as HTMLElement).style.top = `${Y}px`;
        }
    }


    checkHeadBoy(){
        //获取所有身体循环判读撞身体
        for (let i = 1;i < this.bodies.length;i++) {
            let bd = this.bodies[i] as HTMLElement;
            // bd.style.cssText=`background-color:${this.rgb()}`;
            bd.style.backgroundColor=this.rgb()
            if (this.X=== bd.offsetLeft && this.Y===bd.offsetTop) {
                throw new Error("撞身体了，阿欧！")
            }
            
        }
    }

    rgb(){//rgb颜色随机
        let rgb = [];
        for(let i=0;i<3;++i){
            let color = Math.floor(Math.random()*256).toString(16);
             //Math.random()*256是生成0-256之间的随机小数，Math.floor取整
            color = color.length == 1?'0'+color:color;
            rgb.push(color);
            }
            return '#' + rgb.join('');
    }

}   

export default Snake